package com.kotlinx.view.carDialog

import android.animation.ValueAnimator
import android.app.Activity
import android.content.res.Resources
import android.graphics.Color
import android.graphics.PointF
import android.view.View
import android.view.animation.Animation
import android.view.animation.LinearInterpolator
import android.view.animation.TranslateAnimation
import android.widget.TextView
import androidx.constraintlayout.widget.Guideline
import androidx.core.view.isVisible
import com.kotlinx.view.R
import com.kotlinx.view.base.YBaseDialog
import com.kotlinx.view.color.ViewColor
import com.kotlinx.view.databinding.YDialogCarBinding
import com.kotlinx.view.utils.ViewThread
import com.kotlinx.view.utils.YDrawableUtils


/**
 * 输入车牌号弹窗
 * @author yujing 2023年8月30日14:29:35
 */
/*
val dialog = YViewCarDialog(this).apply {
    default = "京"
    okListener = {
        YToast.show(it)
        TTS.speak(it)
        dismiss()
    }
    show()
}

//自定义颜色
val dialog = YViewCarDialog(this).apply {
    default = "川"
    okListener = {
        YToast.show(it)
        TTS.speak(it)
        dismiss()
    }
    viewColor.apply {
        //车牌号键盘 提示文字颜色
         carKeyboardTipsColor = Color.parseColor("#888888")
        //车牌号键盘 省文字颜色
         carKeyboardProvinceColor = Color.parseColor("#FF5555")
        //车牌号键盘 号码文字颜色
         carKeyboardNumberColor = Color.parseColor("#00FF00")
        //车牌号键盘 确定文字颜色
         carKeyboardConfirmColor =  Color.parseColor("#0EFAAE")
        //车牌号键盘 按键文字颜色
        carKeyboardKeysColor = Color.parseColor("#0E8ADE")
        //车牌号键盘 其他按键（省份）文字颜色
        carKeyboardKeysOtherColor = Color.parseColor("#EE3ADE")
    }
    show()
}
 */
class YViewCarDialog(activity: Activity) : YBaseDialog<YDialogCarBinding>(activity, R.layout.y_dialog_car, android.R.style.Theme_DeviceDefault_Dialog_NoActionBar) {
    //标题
    var titleText: CharSequence = "指定车牌"

    //颜色
    var viewColor: ViewColor

    //文字大小比例
    var viewSizeScale = 1.0f

    //默认值
    var default = ""

    //最后确定监听
    var okListener: ((String) -> Unit)? = null

    //默认是否显示键盘
    var defaultShowKeyboard = true

    //初始化完成
    var initCompleteListener: ((YDialogCarBinding) -> Unit)? = null

    val provinceList = arrayListOf<CharSequence>(
        "川", "京", "沪", "鄂", "湘", "渝", "粤", "闽", "晋", "黑",
        "津", "浙", "豫", "赣", "贵", "青", "琼", "宁", "吉", "蒙",
        "冀", "苏", "皖", "桂", "云", "陕", "甘", "藏", "新", "辽",
        "鲁", "澳", "港", "学"
    )
    val alphabetList = arrayListOf<CharSequence>(
        "0", "1", "2", "3", "4", "5", "6", "7", "8", "9",
        "Q", "W", "E", "R", "T", "Y", "U", "O", "P", "L",
        "A", "S", "D", "F", "G", "H", "J", "K", "N", "M",
        "Z", "X", "C", "V", "B"
    )

    private var provinceViewList: MutableList<TextView> = ArrayList()
    private var alphabetViewList: MutableList<TextView> = ArrayList()

    init {
        this.viewColor = ViewColor(activity)
        viewColor.buttonOkTextColor = Color.parseColor("#FFFFFF")
        viewColor.pressedFalseButtonOkColor = Color.parseColor("#FFE9A633")
        viewColor.buttonCancelTextColor = Color.parseColor("#FFE9A633")

        strokeColor = Color.parseColor("#00000000") //边框颜色
        fillColor = Color.parseColor("#00000000") //填充颜色

        val width = Resources.getSystem().displayMetrics.widthPixels
        val height = Resources.getSystem().displayMetrics.heightPixels
        //如果是竖屏
        if (height > width) {
            widthPixels = 1F
            heightPixels = 1F
            viewSizeScale = 1.2f
            roundRadius = 0F
            fullscreen = false //全屏
        } else {
            widthPixels = 0.45f //宽
            heightPixels = 1f //高
            viewSizeScale = 1.0f
            roundRadius = 0F
            fullscreen = true //全屏
        }
    }

    override fun init() {
        binding.run {
            tvTitle.text = titleText
            //设置默认值
            if (default.isNotEmpty()) {
                tvProvince.text = default.substring(0, 1)
                if (default.length > 1) {
                    tvNumber.text = default.substring(1, default.length)
                }
                showKeys(2)//有默认值就显示字母
            } else {
                showKeys(1)//无默认值就显示省份
            }
            //设置省份
            provinceViewList = arrayListOf(
                tvKey01, tvKey02, tvKey03, tvKey04, tvKey05, tvKey06, tvKey07, tvKey08, tvKey09, tvKey10,
                tvKey11, tvKey12, tvKey13, tvKey14, tvKey15, tvKey16, tvKey17, tvKey18, tvKey19, tvKey20,
                tvKey21, tvKey22, tvKey23, tvKey24, tvKey25, tvKey26, tvKey27, tvKey28, tvKey29, tvKey30,
                tvKey31, tvKey32, tvKey33, tvKey34
            )
            for (i in 0..<provinceViewList.size) {
                provinceViewList[i].text = provinceList[i]
                //监听省份按下
                provinceViewList[i].setOnClickListener {
                    showKeys(2)//切换到字母
                    if (it is TextView) tvProvince.text = it.text.toString()
                    tvNumber.text = ""//切换了省份，就需要重新输入车牌号
                }
            }

            //无牌按下
            tvKeyNull.setOnClickListener {
                showKeys(2)//切换到字母
                if (it is TextView) tvProvince.text = "无"
                tvNumber.text = ""//切换了省份，就需要重新输入车牌号
            }

            //设置字母
            alphabetViewList = arrayListOf(
                tvKey101, tvKey102, tvKey103, tvKey104, tvKey105, tvKey106, tvKey107, tvKey108, tvKey109, tvKey110,
                tvKey111, tvKey112, tvKey113, tvKey114, tvKey115, tvKey116, tvKey117, tvKey118, tvKey119, tvKey120,
                tvKey121, tvKey122, tvKey123, tvKey124, tvKey125, tvKey126, tvKey127, tvKey128, tvKey129, tvKey130,
                tvKey131, tvKey132, tvKey133, tvKey134, tvKey135
            )
            for (i in 0..<alphabetViewList.size) {
                alphabetViewList[i].text = alphabetList[i]
                //监听字母按下
                alphabetViewList[i].setOnClickListener {
                    if (it is TextView) {
                        tvNumber.text = tvNumber.text.toString() + it.text.toString()
                    }
                }
            }

            //删除
            val deleteListener = View.OnClickListener {
                tvNumber.text = tvNumber.text.toString().let { if (it.isEmpty()) "" else it.substring(0, it.length - 1) }
            }
            llKeyDelete01.setOnClickListener(deleteListener)
            llKeyDelete02.setOnClickListener(deleteListener)

            llBottom.post {
                //默认是否显示键盘
                if (defaultShowKeyboard) {
                    ViewThread.runOnUiThreadDelayed({
                        llBottom.isVisible = true
                        llBottom.startAnimation(showAnimation())
                        openKeyboard(glLine01, true)
                    }, 300)
                }
            }

            //输入省份
            llProvince.setOnClickListener {
                showKeys(1)//切换到省份
                if (!llBottom.isVisible) {
                    llBottom.isVisible = true
                    llBottom.startAnimation(showAnimation())
                    openKeyboard(glLine01, true)
                }
            }

            //输入号码
            llNumber.setOnClickListener {
                showKeys(2)//切换到字母
                if (!llBottom.isVisible) {
                    llBottom.isVisible = true
                    llBottom.startAnimation(showAnimation())
                    openKeyboard(glLine01, true)
                }
            }

            //确定
            tvNumberOk.setOnClickListener {
                llBottom.isVisible = false
                binding.llBottom.startAnimation(hideAnimation())
                openKeyboard(glLine01, false)
            }

            //切换
            tvChange01.setOnClickListener {
                showKeys(2)//切换到字母
            }
            tvChange02.setOnClickListener {
                showKeys(1)//切换到省份
            }
            //空白区域
            clTop.setOnClickListener {
                dismiss()
            }
            //弹窗区域
            llDialog.setOnClickListener {}

            //最后确定
            btOk.setOnClickListener {
                okListener?.invoke(tvProvince.text.toString() + tvNumber.text.toString())
            }

            //关闭
            btCancel.setOnClickListener {
                dismiss()
            }
        }


        //---------------------------缩放 开始---------------------------
        if (viewSizeScale != 1.0f) {
            binding.run {
                //设置文字放大缩小倍数
                tvTitle.run { textSize = px2sp(textSize.toInt()) * viewSizeScale } //标题
                btCancel.run { textSize = px2sp(textSize.toInt()) * viewSizeScale }//取消按钮
                btOk.run { textSize = px2sp(textSize.toInt()) * viewSizeScale }//确定按钮

                tvTips.run { textSize = px2sp(textSize.toInt()) * viewSizeScale } //提示
                tvProvince.run { textSize = px2sp(textSize.toInt()) * viewSizeScale } //省份
                tvNumber.run { textSize = px2sp(textSize.toInt()) * viewSizeScale } //号码
                tvNumberOk.run { textSize = px2sp(textSize.toInt()) * viewSizeScale }//键盘确定按钮

                for (i in 0..<provinceViewList.size) {
                    provinceViewList[i].run { textSize = px2sp(textSize.toInt()) * viewSizeScale }
                }
                for (i in 0..<alphabetViewList.size) {
                    alphabetViewList[i].run { textSize = px2sp(textSize.toInt()) * viewSizeScale }
                }
                //切换
                tvChange01.run { textSize = px2sp(textSize.toInt()) * viewSizeScale }
                tvChange02.run { textSize = px2sp(textSize.toInt()) * viewSizeScale }
                tvKeyNull.run { textSize = px2sp(textSize.toInt()) * viewSizeScale }
            }
        }
        //---------------------------缩放 结束---------------------------


        //---------------------------设置颜色 开始---------------------------
        binding.run {
            llTitle.setBackgroundColor(viewColor.titleBackgroundColor)
            ivTitleDivider.setBackgroundColor(viewColor.titleDividerColor)
            llContent.setBackgroundColor(viewColor.contentBackgroundColor)

            tvTitle.setTextColor(viewColor.titleTextColor) //标题
            btCancel.setTextColor(viewColor.buttonCancelTextColor) //取消按钮
            btOk.setTextColor(viewColor.buttonOkTextColor) //确定按钮

            tvTips.setTextColor(viewColor.carKeyboardTipsColor) //提示
            tvProvince.setTextColor(viewColor.carKeyboardProvinceColor) //省份
            tvNumber.setTextColor(viewColor.carKeyboardNumberColor) //号码
            tvNumberOk.setTextColor(viewColor.carKeyboardConfirmColor) //键盘确定按钮

            for (i in 0..<provinceViewList.size) {
                provinceViewList[i].setTextColor(viewColor.carKeyboardKeysColor)
            }
            for (i in 0..<alphabetViewList.size) {
                alphabetViewList[i].setTextColor(viewColor.carKeyboardKeysColor)
            }
            tvChange01.setTextColor(viewColor.carKeyboardKeysOtherColor)
            tvChange02.setTextColor(viewColor.carKeyboardKeysOtherColor)
            tvKeyNull.setTextColor(viewColor.carKeyboardKeysOtherColor)

            //圆角
            val radius = dp2px(5F).toFloat()
            val focusedDrawableOk = YDrawableUtils.createGradientDrawable(viewColor.focusedTrueButtonOkColor, 0, Color.WHITE, radius, radius, radius, radius)
            val pressedDrawableOk = YDrawableUtils.createGradientDrawable(viewColor.pressedTrueButtonOkColor, 0, Color.WHITE, radius, radius, radius, radius)
            val normalDrawableOk = YDrawableUtils.createGradientDrawable(viewColor.pressedFalseButtonOkColor, 0, Color.WHITE, radius, radius, radius, radius)
            btOk.background = YDrawableUtils.createStateListDrawable(focusedDrawableOk, pressedDrawableOk, normalDrawableOk)

            val focusedDrawableCancel = YDrawableUtils.createGradientDrawable(viewColor.focusedTrueButtonCancelColor, 1, Color.parseColor("#FFE9A633"), radius, radius, radius, radius)
            val pressedDrawableCancel = YDrawableUtils.createGradientDrawable(viewColor.pressedTrueButtonCancelColor, 1, Color.parseColor("#FFE9A633"), radius, radius, radius, radius)
            val normalDrawableCancel = YDrawableUtils.createGradientDrawable(viewColor.pressedFalseButtonCancelColor, 1, Color.parseColor("#FFE9A633"), radius, radius, radius, radius)
            btCancel.background = YDrawableUtils.createStateListDrawable(focusedDrawableCancel, pressedDrawableCancel, normalDrawableCancel)
        }
        //---------------------------设置颜色 结束---------------------------

        initCompleteListener?.invoke(binding)
    }

    //显示省份键盘或者字母键盘。1省份  2字母
    private fun showKeys(type: Int) {
        if (type == 1) {
            binding.llKeysProvince.isVisible = true
            binding.llKeysAlphabet.isVisible = false
        } else {
            binding.llKeysProvince.isVisible = false
            binding.llKeysAlphabet.isVisible = true
        }
    }

    //显示动画
    private fun showAnimation(): TranslateAnimation {
        //从下往上
        return TranslateAnimation( //坐标类型，x初始值，坐标类型，x结束值
            Animation.RELATIVE_TO_SELF, 0f, Animation.RELATIVE_TO_SELF, 0f,
            Animation.RELATIVE_TO_SELF, 1f, Animation.RELATIVE_TO_SELF, 0f
        ).apply {
            duration = 300 //时长
        }
    }

    //隐藏动画
    private fun hideAnimation(animationEnd: (() -> Unit)? = null): TranslateAnimation {
        //从上往下
        return TranslateAnimation( //坐标类型，x初始值，坐标类型，x结束值
            Animation.RELATIVE_TO_SELF, 0f, Animation.RELATIVE_TO_SELF, 0f,
            Animation.RELATIVE_TO_SELF, 0f, Animation.RELATIVE_TO_SELF, 1f
        ).apply {
            duration = 300 //时长
            setAnimationListener(object : Animation.AnimationListener {
                override fun onAnimationStart(animation: Animation?) {

                }

                override fun onAnimationEnd(animation: Animation?) {
                    binding.llBottom.isVisible = false
                    ViewThread.runOnUiThreadDelayed({
                        animationEnd?.invoke()
                    }, 1)
                }

                override fun onAnimationRepeat(animation: Animation?) {}
            })
        }
    }

    //打开或关闭列表动画， 缩放
    private fun openKeyboard(view: Guideline, isOpen: Boolean) {
        val point = PointF(0F, 0F)
        ValueAnimator().apply {
            duration = 300 // 时间
            setObjectValues(point) // 初始值或者对象
            interpolator = LinearInterpolator()
            // 自定义动画算法
            setEvaluator { fraction, _, _ ->
                if (isOpen) {
                    //1 ~ 0.68
                    point.y = 1f - (fraction * 0.32f)
                } else {
                    //0.68 ~ 1
                    point.y = 0.68f + (fraction * 0.32f)
                }
                point
            }
            // 动画运动更改状态触发的方法
            addUpdateListener { animation ->
                val pointF = animation.animatedValue as PointF
                view.setGuidelinePercent(pointF.y)
            }
            start()
        }
    }

    override fun dismiss() {
        //如果是显示键盘，先隐藏键盘
        if (binding.llBottom.isVisible) {
            //缩放
            openKeyboard(binding.glLine01, false)
            //隐藏键盘
            binding.llBottom.startAnimation(hideAnimation {
                super.dismiss()
            })
        } else {
            super.dismiss()
        }
    }
}
